package cn.chendd.shiro.examples.controller;

import cn.chendd.shiro.examples.commponent.EncryptionRealmEhCache;
import cn.chendd.shiro.examples.model.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.realm.Realm;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

/**
 * @author chendd
 * @date 2019/6/29 23:01
 * 动态权限加载
 */
@Controller
@RequestMapping("/dynamicPermission")
public class DynamicPermissionController {

    /**
     * 使用更新缓存的方式重载缓存中的权限，仅限学习测试使用
     * 从缓存中获取用户Realm，找到当前用户的角色权限信息，实现动态增加
     */
    @RequestMapping("/reloadPermission")
    public String reloadPermission(){
        //更新缓存中的用户角色与权限对象
        RealmSecurityManager realmSecurityManager = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        Collection<Realm> realms = realmSecurityManager.getRealms();
        for (Realm realm : realms) {
            if(realm instanceof EncryptionRealmEhCache){
                EncryptionRealmEhCache encryptionRealm = (EncryptionRealmEhCache) realm;
                Cache<Object, AuthorizationInfo> authorizationCache = encryptionRealm.getAuthorizationCache();
                if(authorizationCache == null){
                    continue;
                }
                Set<Object> keys = authorizationCache.keys();
                Iterator<Object> iterator = keys.iterator();
                while (iterator.hasNext()){
                    Object object = iterator.next();
                    if(object.toString().startsWith(SysUser.class.getName())){
                        if(! SecurityUtils.getSubject().getPrincipal().toString().equals(object.toString())){
                            continue;
                        }
                        SimpleAuthorizationInfo author = (SimpleAuthorizationInfo) authorizationCache.get(object);
                        author.addStringPermission("user:queryList");
                        author.addRole("userManager");
                    }
                }
            }
        }
        return "success";
    }

    //使用Realm清空用户权限
    @RequestMapping("/clearPermission")
    @ResponseBody
    public void clearPermission(){

    }

}
